<template>
  <div>{{ hours }} : {{ minutes }} : {{ seconds }}</div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from "vue";
const props = defineProps({
  duration: {
    type: Number,
    defaullt: 0
  }
});

const endTime = ref(props.duration); // 假设倒计时1小时
const hours = ref(0);
const minutes = ref(0);
const seconds = ref(0);
const countdown = () => {
  const milliseconds = endTime.value;
  hours.value = formatTime(Math.floor(milliseconds / 3600));
  minutes.value = formatTime(Math.floor(milliseconds / 60) % 60);
  seconds.value = formatTime(Math.floor(milliseconds % 60));
};

const formatTime = value => {
  // 对于小于10的数值补0
  return value.toString().padStart(2, "0");
};

const intervalId = ref(null);
const emit = defineEmits(["endTimeClear"]);
onMounted(() => {
  intervalId.value = setInterval(() => {
    if (endTime.value > 0) {
      endTime.value--;
      countdown();
    } else {
      emit("endTimeClear");
      clearInterval(intervalId.value);
    }
  }, 1000);
});

onBeforeUnmount(() => {
  clearInterval(intervalId.value);
});
</script>
